package com.whty.cms.filewps.common.controller;

import cn.hutool.http.*;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.whty.cms.filewps.common.message.ResponseMessage;
import com.whty.cms.filewps.upload.dto.AttachFile;
import com.whty.cms.filewps.upload.dto.AttachVersion;
import com.whty.cms.filewps.upload.dto.TeamworkLesson;
import com.whty.cms.filewps.upload.service.ILessonService;
import com.whty.cms.filewps.upload.service.IUploadService;
import com.whty.cms.filewps.upload.service.IVersionService;
import com.whty.cms.filewps.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Desc  wps对接接口服务
 * @Auth  fengc
 *
 */
@RestController
public class FileInfoController {
    private static final Logger LOG = LoggerFactory.getLogger(FileInfoController.class);

    final static String applyType="3d3080afd6194d5cabef845ebff66829";

    @Autowired
    private IUploadService uploadService;

    @Autowired
    private IVersionService versionService;

    @Autowired
    private ILessonService lessonService;

    public static long getSecondTimestamp(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime()/1000);
        return Integer.valueOf(timestamp);
    }

    public static Date dateToStamp(String s) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        return date;
    }

    /**
     * 获取文件信息
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/v4/v1/3rd/file/info")
    @ResponseBody
    public JSONObject getFileInfo(HttpServletRequest request) throws Exception {
        JSONObject finalJson = new JSONObject();
        JSONObject fileJson = new JSONObject();
        JSONObject userJson = new JSONObject();

        TeamworkLesson lesson = new TeamworkLesson();
        String userId = null;
        String userName = null;
        String avatarUrl = null;
        String fileName = null;
        String fid = request.getHeader("x-weboffice-file-id");
        LOG.info("wps-4开始回调"+fid+"文件信息");
        if(StringUtils.isBlank(fid)){
            finalJson.put("msg","回调参数fid不存在");
            return finalJson;
        }




        net.sf.json.JSONObject json = new net.sf.json.JSONObject();
        Integer version = versionService.getMaxVerion(fid);
        if(version==null){
            version=1;
        }

        if(version==1){
            json = EsUtil.searchDoc(fid);
            userId = json.optString("userId");
            userName = "天喻";
            avatarUrl = "https://css.huijiaoyun.com/tianyu_edu/area/999999/images/logo/edu.ico";

        }else{
            AttachVersion cond = new AttachVersion();
            cond.setpId(fid);
            cond.setVersion(version);
            AttachVersion av = versionService.getVersion(cond);
            json = EsUtil.searchDoc(String.valueOf(av.getFid()));
            userId = av.getUserId();
            userName = av.getUserName();
            avatarUrl = av.getAvatarUrl();
        }


        if(StringUtils.isNotBlank(request.getParameter("_w_third_userId"))) {
            userId = request.getParameter("_w_third_userId");
        }
        if(StringUtils.isNotBlank(request.getParameter("_w_third_userName"))) {
            userName = request.getParameter("_w_third_userName");
        }
        if(StringUtils.isNotBlank(request.getParameter("_w_third_avatarUrl"))) {
            avatarUrl = request.getParameter("_w_third_avatarUrl");
        }
        if(StringUtils.isNotBlank(request.getParameter("_w_third_fileName"))) {
            fileName = request.getParameter("_w_third_fileName");
        }


        String permission;

        permission = request.getParameter("_w_third_permission");
        if(StringUtils.isBlank(permission)){
            lesson.setFid(fid);
            lesson.setStatus("1");
            lesson.setType("1");
            lesson.setUserId(userId);
            int num = lessonService.selectCount(lesson);//查询是否是发起人
            if(num>0){
                permission = "read";
            }else{
                permission = "write";
            }
        }

        LOG.info(fid+"文档权限per:"+permission);



        String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
        String customSourceUrl = MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-customSourceBucket");

        if(fileName==null) {
            fileName = json.getString("fileName");
            if (fileName.lastIndexOf("\\") > 0) {
                fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
            }
        }
        fileJson.put("id",fid);
        fileJson.put("name",fileName);
        fileJson.put("version",version);
        fileJson.put("size",json.getInt("fileLength"));
        fileJson.put("creator",json.getString("userId"));
        fileJson.put("create_time",getSecondTimestamp(dateToStamp(json.getString("postedTime"))));
        fileJson.put("modifier",json.getString("userId"));
        fileJson.put("modify_time",getSecondTimestamp(new Date()));

        fileJson.put("preview_pages",0);
        String url = CosUtil.getAuthDownloadUrl(json.getString("filePath"),json.getString("applyType"));
        //吉林存储桶下载地址替换为自定义域名
        if(StringUtils.isNotBlank(customSourceUrl)){
            url = url.replace(url.substring(0,url.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
        }
        fileJson.put("download_url",url);

        userJson.put("id",userId);
        userJson.put("name",userName);
        userJson.put("permission",permission);
        userJson.put("avatar_url",avatarUrl);

        finalJson.put("file",fileJson);
        finalJson.put("user",userJson);
        return finalJson;
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/v4/v1/3rd/user/info")
    @ResponseBody
    public JSONObject getUserInfo(HttpServletRequest request,@RequestBody JSONObject obj) throws Exception {
        String url = "https://openapigateway.huijiaoyun.com";
        JSONObject finalJson = new JSONObject();
        JSONArray userArr = new JSONArray();
        JSONObject userJson1 = new JSONObject();
        userJson1.put("id","a7e33f16f00511eb9b1a020315540695");
        userJson1.put("name","胡灿");
        userJson1.put("permission","write");
        userJson1.put("avatar_url","https://css.huijiaoyun.com/tianyu_edu/common/images/nophoto_mid.gif?_r=1675925646");

        JSONObject userJson2 = new JSONObject();
        userJson2.put("id","0b2ad34c934911eab65a020315ff211d");
        userJson2.put("name","代昌盛");
        userJson2.put("permission","write");
        userJson2.put("avatar_url","https://css.huijiaoyun.com/tianyu_edu/common/images/nophoto_mid.gif?_r=1675925773");

        userArr.add(userJson1);
        userArr.add(userJson2);
        //String fid = request.getHeader("x-weboffice-file-id");
        /*LOG.info("附件id信息："+fid);
        LOG.info("wps-4开始回调"+fid+"用户信息");
        JSONArray arr = obj.getJSONArray("ids");
        String platformCode = obj.getStr("platformCode");
        String prefixUrl = "";
        if(StringUtils.isBlank(fid)){
            finalJson.put("msg","回调参数fid不存在");
            return finalJson;
        }

        String apiUrl = url + "/cms-gateway/selectPlatformInfo/"+platformCode+"?&accessToken=" + HttpClient.getAccessToken(url);
        String response = new HttpClient(apiUrl).doGet();
        net.sf.json.JSONObject api = net.sf.json.JSONObject.fromObject(response);
        if ("000000".equals(api.getString("result"))) {
            net.sf.json.JSONObject apiInfo = api.getJSONObject("data");
            prefixUrl = apiInfo.optString("CMS_GATEWAY_URL");
        }

        for(int i=0;i<arr.size();i++){
            JSONObject userJson = new JSONObject();
            String userId = (String) arr.get(i);
            String aamUrl = prefixUrl + "/user/api/user/get-user-info?user_id=" + userId + "&accessToken=" + HttpClient.getAccessToken(prefixUrl);
            String response1 = new HttpClient(aamUrl).doGet();
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(response1);
            if ("000000".equals(json.getString("code"))) {
                net.sf.json.JSONObject userinfo = json.getJSONObject("result");
                net.sf.json.JSONObject avatar = userinfo.getJSONObject("avatar");
                userJson.put("id",userId);
                userJson.put("name",userinfo.getString("name"));
                userJson.put("permission","write");
                userJson.put("avatar_url",avatar.getString("1"));
            }

            userArr.add(userJson);
        }*/
        finalJson.put("users",userArr);
        return finalJson;
    }



    /**
     * 上传文件新版本
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/v4/v1/3rd/file/save")
    @ResponseBody
    public JSONObject saveFile(HttpServletRequest request) throws Exception {
        JSONObject finalJson = new JSONObject();
        JSONObject fileJson = new JSONObject();
        String fid = request.getHeader("x-weboffice-file-id");
        Integer version = versionService.getMaxVerion(fid);
        if(version==null){
            version=1;
        }
        String saveType = request.getHeader("X-Weboffice-Save-Type");
        LOG.info("自动保存类型saveType::"+saveType);
        if(StringUtils.isBlank(fid)||StringUtils.isBlank(saveType)){
            finalJson.put("msg","回调必填参数未传递");
            return finalJson;
        }

        Part part = request.getPart("file");
        String userId = request.getParameter("_w_third_userId");
        LOG.info("保存的用户id："+userId);
        String fileName = request.getParameter("_w_third_fileName");
        String userName = request.getParameter("_w_third_userName");
        String avatarUrl = request.getParameter("_w_third_avatarUrl");
        String resId = request.getParameter("_w_third_resId");
        String from = request.getParameter("_w_third_from");
        //String applyType = request.getParameter("applyType");
        //String sourceType = request.getParameter("sourceType");
        //String platformCode = request.getParameter("platformCode");
        Long fileLength = part.getSize();
        String fileMd5 = DigestUtils.md5Hex(part.getInputStream());
        String fileExt = "";
        int idx = fileName.lastIndexOf(".");
        if (idx != -1) {
            fileExt = fileName.substring(idx + 1);
        }
        //String cosKey = CosUtil.getCosKey(fileName, userId, platformCode);
        AttachFile attach = new AttachFile();
        AttachVersion attachVersion = new AttachVersion();
        //attach.setFid(Long.parseLong(fid));
        attach.setUserId(userId);
        attach.setFileName(fileName);
        attach.setFileExt(fileExt);
        attach.setFileLength(fileLength);
        attach.setFileMd5(fileMd5);
        attach.setApplyType(applyType);
        attach.setSourceType("b49ac4183f1311e9bcfd00fec0a8c9c9");
        attach.setPlatformCode("999999");
        attach = uploadService.SimpleUploadFile(attach,part.getInputStream());
        attachVersion.setFid(attach.getFid());
        attachVersion.setpId(fid);
        attachVersion.setVersion(version+1);
        attachVersion.setUserId(userId);
        attachVersion.setUserName(userName);
        attachVersion.setAvatarUrl(avatarUrl);
        versionService.save(attachVersion);
        LOG.info("附件id信息："+fid);
        LOG.info("wps-4开始回调"+fid+"用户信息");
        String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
        String customSourceUrl = MemcacheUtil.getDatabaseObj(applyType+"-customSourceBucket");
        String url = CosUtil.getAuthDownloadUrl(attach.getFilePath(),applyType);
        if(StringUtils.isNotBlank(customSourceUrl)){
            url = url.replace(url.substring(0,url.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
        }

        fileJson.put("id",fid);
        fileJson.put("name",fileName);
        fileJson.put("version",version+1);
        fileJson.put("size",fileLength);
        fileJson.put("download_url",url);


        if(StringUtils.isNotBlank(resId)&&"rrtpc".equals(from)) {
            String postUrl = "https://gateway.huijiaoyun.com/rrtbk-api/cloud/updateRes?accessToken="+HttpClient.getAccessToken("https://gateway.huijiaoyun.com");
            String previewUrl = WPSEdit.getpreviewUrl(attach);
            JSONObject json = new JSONObject();
            json.put("resId",resId);
            json.put("previewUrl",previewUrl);
            json.put("downUrl",url);
            LOG.info("更新资源Id:"+resId+"信息"+json.toString());
            LOG.info("修改请求地址"+postUrl);
            String response = new HttpClient(new URL(postUrl)).doPost(json.toString());
            LOG.info("修改结果"+response);
        }



        finalJson.put("file",fileJson);
        return finalJson;
    }



    /**
     * 文件重命名
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/v4/v1/3rd/file/rename")
    @ResponseBody
    public ResponseMessage renameFile(HttpServletRequest request, @RequestBody JSONObject obj) throws Exception {
        ResponseMessage result = new ResponseMessage();

        String fid = request.getHeader("x-weboffice-file-id");
        if(StringUtils.isBlank(fid)){
            result.setMsg("回调参数fid不存在");
            return result;
        }
        LOG.info("附件id信息："+fid);
        LOG.info("wps-4开始回调"+fid+"用户信息");
        String name = obj.getStr("name");
        net.sf.json.JSONObject es = EsUtil.searchDoc(fid);
        AttachFile attachFile = uploadService.selectByPrimaryKey(Long.parseLong(fid));
        attachFile.setFileName(name);
        uploadService.updateByPrimaryKey(attachFile);
        es.put("fileName",name);
        EsUtil.addOrUpdateDoc(fid, es.toString());
        return ResponseMessage.returnMessage(result, "000000", "成功",null);
    }


    /**
     * 通知此文件目前有哪些人正在协作
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/v4/v1/3rd/file/online")
    @ResponseBody
    public ResponseMessage notifyOnlineUser(HttpServletRequest request,@RequestBody JSONObject obj) throws Exception {
        ResponseMessage result = new ResponseMessage();

        String fid = request.getHeader("x-weboffice-file-id");
        LOG.info("附件id信息："+fid);
        LOG.info("wps-4开始回调"+fid+"用户信息");
        JSONArray arr = obj.getJSONArray("ids");

        if(StringUtils.isBlank(fid)){
            result.setMsg("回调参数fid不存在");
            return result;
        }
        return ResponseMessage.returnMessage(result, "000000", "成功",null);
    }

    /**
     * 回调通知
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/v4/v1/3rd/onnotify")
    @ResponseBody
    public ResponseMessage onnotify(HttpServletRequest request,@RequestBody JSONObject obj) throws Exception {
        ResponseMessage result = new ResponseMessage();

        String fid = request.getHeader("x-weboffice-file-id");
        LOG.info("附件id信息："+fid);
        LOG.info("wps-4开始回调"+fid+"用户信息");
        JSONArray arr = obj.getJSONArray("ids");

        if(StringUtils.isBlank(fid)){
            result.setMsg("回调参数fid不存在");
            return result;
        }
        return ResponseMessage.returnMessage(result, "000000", "成功",null);
    }


    @RequestMapping("/v4/v1/3rd/file/version/{version}")
    @ResponseBody
    public JSONObject getPreload(HttpServletRequest request,@PathVariable Integer version) throws Exception {
        net.sf.json.JSONObject json = new net.sf.json.JSONObject();
        JSONObject finalJson = new JSONObject();
        JSONObject fileJson = new JSONObject();
        String fid = request.getHeader("x-weboffice-file-id");
        LOG.info("附件id信息："+fid);
        LOG.info("开始回调"+fid+"第"+version+"版信息");
        if(StringUtils.isBlank(fid)){
            finalJson.put("msg","回调参数fid不存在");
            return finalJson;
        }

        if(version==1){
            json = EsUtil.searchDoc(fid);

        }else{
            AttachVersion cond = new AttachVersion();
            cond.setpId(fid);
            cond.setVersion(version);
            AttachVersion av = versionService.getVersion(cond);
            json = EsUtil.searchDoc(String.valueOf(av.getFid()));
        }

        String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
        String customSourceUrl = MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-customSourceBucket");

        String fileName = json.getString("fileName");
        if(fileName.lastIndexOf("\\") > 0) {
            fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
        }
        fileJson.put("id",fid);
        fileJson.put("name",fileName);
        fileJson.put("version",version);
        fileJson.put("size",json.getInt("fileLength"));
        fileJson.put("creator",json.getString("userId"));
        fileJson.put("create_time",getSecondTimestamp(dateToStamp(json.getString("postedTime"))));
        fileJson.put("modifier",json.getString("userId"));
        fileJson.put("modify_time",getSecondTimestamp(dateToStamp(json.getString("postedTime"))));

        String url = CosUtil.getAuthDownloadUrl(json.getString("filePath"),json.getString("applyType"));
        //吉林存储桶下载地址替换为自定义域名
        if(StringUtils.isNotBlank(customSourceUrl)){
            url = url.replace(url.substring(0,url.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
        }
        fileJson.put("download_url",url);
        finalJson.put("file",fileJson);

        return finalJson;
    }



    @RequestMapping("/v4/v1/3rd/file/history")
    @ResponseBody
    public JSONObject history(HttpServletRequest request) throws Exception {
        JSONArray arr = new JSONArray();
        JSONObject finalJson = new JSONObject();
        JSONObject version1Json = new JSONObject();
        JSONObject createUser1Json = new JSONObject();
        JSONObject modifyUser1Json = new JSONObject();

        String fid = request.getHeader("x-weboffice-file-id");
        /*Integer offset = obj.getInt("offset");
        Integer count= obj.getInt("count");*/
        //LOG.info("历史信息："+offset+"---"+count);
        LOG.info("附件id信息："+fid);
        LOG.info("wps-4开始回调"+fid+"历史版本信息");

        if(StringUtils.isBlank(fid)){
            finalJson.put("msg","回调参数fid不存在");
            return finalJson;
        }
        net.sf.json.JSONObject json = EsUtil.searchDoc(fid);
        LOG.info("附件存在es中信息："+json);
        String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
        String customSourceUrl = MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-customSourceBucket");

        String fileName = json.getString("fileName");

        String url1 = CosUtil.getAuthDownloadUrl(json.getString("filePath"),json.getString("applyType"));
        //吉林存储桶下载地址替换为自定义域名
        if(StringUtils.isNotBlank(customSourceUrl)){
            url1 = url1.replace(url1.substring(0,url1.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
        }

        version1Json.put("id",fid);
        version1Json.put("name",fileName);
        version1Json.put("version",1);
        version1Json.put("size",json.getInt("fileLength"));
        version1Json.put("create_time",getSecondTimestamp(dateToStamp(json.getString("postedTime"))));
        version1Json.put("modify_time",getSecondTimestamp(dateToStamp(json.getString("postedTime"))));
        version1Json.put("download_url",url1);

        createUser1Json.put("id",json.getString("userId"));
        createUser1Json.put("name","天喻");
        createUser1Json.put("avatar_url","https://css.huijiaoyun.com/tianyu_edu/area/888888/images/head/edu.ico");

        modifyUser1Json.put("id",json.getString("userId"));
        modifyUser1Json.put("name","天喻");
        modifyUser1Json.put("avatar_url","https://css.huijiaoyun.com/tianyu_edu/area/888888/images/head/edu.ico");

        version1Json.put("creator",createUser1Json);
        version1Json.put("modifier",modifyUser1Json);

        List<AttachVersion> list = versionService.getList(fid);
        for(AttachVersion av : list){
            String childFid = String.valueOf(av.getFid());
            net.sf.json.JSONObject childJson = EsUtil.searchDoc(childFid);
            JSONObject fileJson = new JSONObject();
            JSONObject createUserJson = new JSONObject();
            JSONObject modifyUserJson = new JSONObject();
            fileJson.put("id",String.valueOf(av.getFid()));
            fileJson.put("name",childJson.getString("fileName"));
            fileJson.put("version",av.getVersion());
            fileJson.put("size",childJson.getInt("fileLength"));
            fileJson.put("create_time",getSecondTimestamp(dateToStamp(childJson.getString("postedTime"))));
            fileJson.put("modify_time",getSecondTimestamp(dateToStamp(childJson.getString("postedTime"))));
            String url = CosUtil.getAuthDownloadUrl(childJson.getString("filePath"),childJson.getString("applyType"));
            //吉林存储桶下载地址替换为自定义域名
            if(StringUtils.isNotBlank(customSourceUrl)){
                url = url.replace(url.substring(0,url.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
            }
            fileJson.put("download_url",url);
            createUserJson.put("id",av.getUserId());
            createUserJson.put("name",av.getUserName());
            createUserJson.put("avatar_url",av.getAvatarUrl());;

            modifyUserJson.put("id",av.getUserId());
            modifyUserJson.put("name",av.getUserName());
            modifyUserJson.put("avatar_url",av.getAvatarUrl());
            fileJson.put("creator",createUserJson);
            fileJson.put("modifier",modifyUserJson);
            arr.add(fileJson);
        }
        arr.add(version1Json);
        finalJson.put("histories",arr);
        return finalJson;
    }

    public static void main(String[] args) {
        String s = getApiUrl();
        System.out.println(s);
    }

    private static String getApiUrl(){
        String apiUrl="";
        String url = "https://teacher-assistant.ty-gateway.tianyuyun.com/teacher-assistant/api/nacosConfig/getByPlatformCodeKey";
        String appKey="925718526835949568";
        String appSecret="GxRGOAEh5NNWMZwczz8EmsHI7mhYYK5YNwpVsA24V0c=";
        String callStage = "1";//请求环境（1-正式线，2-UAT，3-SIT）
         Map<String, String> querys = new HashMap<String, String>();

        /**
         * 请求头参数
         */

       /* querys.clear();
        querys.put("key", "open_url");
        querys.put("platformCode", "420100");
        querys.put("loginPlatformCode", "420100");*/
        // 请求地址格式化，评球query参数
        String requestUrl = initUrl(url, querys);
        // 初始化http
        HttpRequest http = HttpUtil.createRequest(Method.POST, requestUrl);

        // 签名设置
        Long timestamp = System.currentTimeMillis();
        String authStr = appKey + "&" + Method.POST.name().toUpperCase(Locale.ENGLISH) + "&" + callStage + "&" + timestamp;
        String signature = HmacSHA256Utils.digest(appSecret, authStr);
        http.header(Consts.GATEWAY_APP_KEY, appKey);
        http.header(Consts.GATEWAY_STAGE_KEY, callStage);
        http.header(Consts.GATEWAY_SIGNATURE, signature);
        http.header(Consts.GATEWAY_TIMESTAMP, String.valueOf(timestamp));
        // body设置
        // 根据类型设置Content-Type
        http.header(Header.CONTENT_TYPE, ContentTypeEnum.APPLICATION_JSON.getValue());
        JSONObject json1 = JSONUtil.createObj();
        json1.put("key", "open_url");
        json1.put("platformCode", "420100");
        json1.put("loginPlatformCode", "420100");
        http.body(json1);
        HttpResponse response = http.execute();
        String result = response.body();
        System.out.println(result);
        net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(result);
        if ("000000".equals(json.getString("result"))) {
            net.sf.json.JSONObject apiInfo = json.getJSONObject("data");
            apiUrl = apiInfo.getString("keyValue");
        }
        return apiUrl;
    }

    private static String initUrl(String uri, Map<String, String> querys) {
        StringBuilder sbUrl = new StringBuilder(uri);
        try {
            if (null != querys) {
                StringBuilder sbQuery = new StringBuilder();
                for (Map.Entry<String, String> query : querys.entrySet()) {
                    if (0 < sbQuery.length()) {
                        sbQuery.append(Consts.SPE3);
                    }
                    if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                        sbQuery.append(query.getValue());
                    }
                    if (!StringUtils.isBlank(query.getKey())) {
                        sbQuery.append(query.getKey());
                        if (!StringUtils.isBlank(query.getValue())) {
                            sbQuery.append(Consts.SPE4);
                            sbQuery.append(URLEncoder.encode(query.getValue(), Consts.ENCODING));
                        }
                    }
                }
                if (0 < sbQuery.length()) {
                    sbUrl.append(Consts.SPE5).append(sbQuery);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sbUrl.toString();
    }

    /**
     * 通知此文件目前有哪些人正在协作
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/getversion")
    @ResponseBody
    public ResponseMessage getversion(HttpServletRequest request,@RequestBody JSONObject obj) throws Exception {
        ResponseMessage result = new ResponseMessage();

        String fid =obj.getStr("fid");
        Integer a = versionService.getMaxVerion(fid);
        return ResponseMessage.returnMessage(result, "000000", "成功",a);
    }
}
